﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Utility.Network
{
    class Server
    {
        ~Server()
        {
            listener.Stop();
        }
        public void StartListen(int listenPort)
        {

            listener = new TcpListener(new System.Net.IPEndPoint(0, listenPort));
            listener.Start();
            while (true)
            {
                try
                {
                    Socket client = listener.AcceptSocket();
                    ParameterizedThreadStart thStart = new ParameterizedThreadStart(Server.ReceiveFromClientAndReply);
                    Thread clientThd = new Thread(thStart);
                    thStart(client);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            
        }
        public static void ReceiveFromClient(object client)
        {
            Socket clientSock = client as Socket;
            byte []recvBuf = new byte[1024];


            MemoryStream mStream = new MemoryStream();
            mStream.Position = 0;
            while (true)
            {
                int count = clientSock.Receive(recvBuf,1024,0);
                if (count == 0)
                {
                    break;
                }
                else
                {
                    mStream.Write(recvBuf, 0, count); //将接收到的数据写入内存流
                }
            }
            mStream.Flush();
            mStream.Position = 0;
            
            if (mStream.Capacity > 0)
            {
                
                MessagePacket msg = Serializer.DeSerialize(mStream) as MessagePacket;
                DealWithMessage(msg);
            }
            else
            {
                Console.WriteLine("接收到的数据为空。");
            }
            clientSock.Close();
            mStream.Close();
        }

        public static void ReceiveFromClientAndReply(object client)
        {
            Socket clientSock = client as Socket;
            byte[] recvBuf = new byte[1024];

            clientSock.Receive(recvBuf);
            

            int totalSize = BitConverter.ToInt32(recvBuf, 0);
            byte[] ok = new byte[1];
            clientSock.Send(ok);
            MemoryStream mStream = new MemoryStream();
            mStream.Position = 0;
            int total = 0;
            while (total < totalSize)
            {
                int count = clientSock.Receive(recvBuf, 1024, 0);
                total += count;
                if (count == 0)
                {
                    continue;
                }
                else
                { 
                    mStream.Write(recvBuf, 0, count); //将接收到的数据写入内存流
                }
            }
            mStream.Flush();
            mStream.Position = 0;

            MessagePacket reply = null;
            if (mStream.Capacity > 0)
            {

                MessagePacket msg = Serializer.DeSerialize(mStream) as MessagePacket;
                reply = msg;
                //reply = DealWithMessage(msg);
            }
            else
            {
                Console.WriteLine("接收到的数据为空。");
                reply = DealWithMessage(null);
            }
            MemoryStream tmp = Serializer.Serialize(reply);
            byte[] buf = tmp.ToArray();
            tmp.Close();
            clientSock.Send(BitConverter.GetBytes(buf.Length));
            clientSock.Send(buf);
            clientSock.Close();
            mStream.Close();
        }
        
        //return reply to client and cannot return null
        private static MessagePacket DealWithMessage(MessagePacket msg)
        {
            MessagePacket reply = new MessagePacket(2, "reply", null);
            return reply;
            //return not null;
        }
        private TcpListener listener;
        

    }
}
